// 发送手机验证码业务逻辑 --> 发送验证码到手机

/**
 * 判断是否允许发送验证码
 *
 * @param phone 手机号码
 * @returns 是否允许发送验证码
 */
function shouldAllowSendCode(phone: string | undefined): boolean {
  if (!phone) {
    return false;
  }
  const currentTime = useLodashNow();
  const lastTimeClick = useMyUserLoginStoreStore().lastTimeClick;
  const timeInterval = currentTime - lastTimeClick;
  const intervalInSeconds = useMyUserLoginStoreStore().time * 1000;
  if (timeInterval < intervalInSeconds) {
    const errMessage = localesGetValueForKey("phoneCodeRepeatError", '手机号发送失败,请等待 %{timeout} 秒后重试') as string;
    const timeout: string = Number((currentTime - lastTimeClick) / 1000) + '';
    showFailToast(errMessage.replace('%{timeout}', timeout));
    return false;
  }
  return true;
}

/**
 * 发送验证码到手机
 *
 * @param phone 手机号码
 */
async function sendCodeToPhone(phone: string | undefined) {
  const { data } = await sendCodeAsync({ phone });
  if (data.value) {
    updateLastTimeClick();
    showSuccessToast(localesGetValueForKey('sendPhoneCodeSuccess', '手机验证码发送成功'));
  }
}

/**
 * 更新验证码发送时间
 */
function updateLastTimeClick() {
  useMyUserLoginStoreStore().lastTimeClick = useLodashNow();
}

/**
 * 发送手机验证码，防止连续点击发送验证码
 *
 * @param phone 手机号码
 */
export const useSendPhoneCode = async (phone: string | undefined) => {
  if (shouldAllowSendCode(phone)) {
    try {
      await sendCodeToPhone(phone);
    } catch (error) {
      showFailToast((error as Error)?.message);
    }
  }
}
